-- UIArtifactUpgrade
-- Create by zouyb
-- 神器升级界面

require "game/ui/form/artifact/UIArtifactEffect"

-- UIArtifactUpgrade继承自Layer
UIArtifactUpgrade = class("UIArtifactUpgrade", function()
    return cc.Layer:create();
end);

function UIArtifactUpgrade.create(classId)
    return UIArtifactUpgrade.new(classId);
end

-- 内部函数声明
local resize;

-- 构造函数
function UIArtifactUpgrade:ctor(classId)
    -- 初始化
    self:setName("UIArtifactUpgrade");
    local node = cc.CSLoader:createNode("layout/artifactt/ArtifactUpgrade.csb");
    self:addChild(node);
    self.node = node;
    self.classId = classId;


    self.maxLevel = FormulaM.invoke("GET_ARTIFACT_MAX_LEVEL")

    -- 注册事件处理回调函数
    self:registerEventCallback()

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘前获得强化按钮posY

    self.btnOk = findChildByName(self.node, "CT/btn_ok");
    self.btnOkPosY = self.btnOk:getPositionY();

    -- 重绘
    self:redraw();

    -- 适配
    resize(node);
end

-- 适配
function resize(node)
    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 重绘
function UIArtifactUpgrade:redraw()
    local id = self.classId;

    local node = self.node;
    local CT   = node:getChildByName("CT");
    local BT   = node:getChildByName("BT");
    local funcDescLabel = findChildByName(CT, "func_desc");

        -- 显示标题
    local nameLabel = findChildByName(node, "CT/name");
    local kerning = -3;
    if getLang() == "th" then
        kerning = 0;
    end
    TextStyleM.setTitleStyle(nameLabel);
    nameLabel:setString(ItemM.query(self.classId, "name"));

    -- 获取当前碎片、需求碎片、需求金币数
    local level = ArtifactM.getArtifactLevel(id);
    local curScrapNum = 0;
    local needScrapNum = 0;
    local needRelicNum = 0;
    local needMoneyNum = 0;
    local cost = FormulaM.invoke("CALC_ARTIFACT_UPGRADE_LEVEL_COST", level + 1, id);
    for _, arr in pairs(cost) do
        if arr[1] == 1 then

            if ArtifactM.isArtifactScrap(arr[2]) then
                needScrapNum = arr[3];
                curScrapNum = ItemM.getAmount(ME.user, arr[2]); -- 碎片数
            else
                needRelicNum = arr[3];
            end
        elseif arr[1] == 2 then
            needMoneyNum = arr[3];
        end
    end

    if level == self.maxLevel then
        closeFormByName("UIArtifactUpgrade");
    end

    -- 显示碎片个数
    local scrapNumLabel = findChildByName(CT, "scrap_num");
    TextStyleM.setSubheadStyle(scrapNumLabel);
    scrapNumLabel:setString(string.format(getLocStr("artifact_scrap_num"), curScrapNum));

    -- 图标和等级
    local function initIconAndLevel(index, lv)
        local bg = findChildByName(CT, "artifact"..index.."/bg");
        -- local rank = ItemM.query(id, "rank");
        bg:loadTexture(getFrameBgIconPath("rank_large" .. 1));

        local iconImg = findChildByName(CT, "artifact"..index.."/icon");
        local fileName = ItemM.query(id, "icon");
        iconImg:loadTexture(getItemIconPath(fileName));

        local levelBg = findChildByName(CT, "artifact"..index.."/level_bg");
        levelBg:setVisible(false);

        local levelLabel = findChildByName(CT, "artifact"..index.."/level");
        TextStyleM.setTextStyle(levelLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
        levelLabel:setString("+" .. tostring(lv));
        levelLabel:setVisible(false);

        if lv > 0 then
           levelLabel:setVisible(true);
        end
    end
    initIconAndLevel(1, level);
    initIconAndLevel(2, level + 1);

    -- 获取强化后神器的属性提升
    local rank = EquipM.query(id, "rank");
    local props = FormulaM.invoke("GET_ARTIFACT_LEVEL_PROP", id, level + 1);
    local desc = "";
    for _, prop in pairs(props) do
        local temp = "";
        local row = PropM.getRow(prop[1]);
        if row.rule == "career_strengthen" then
            temp = PropM.getSpecialDesc(prop, id);
        else
            temp = PropM.getPropDesc(prop);
        end
        if #props > 1 then
            temp = temp .. " ";
        end
        desc = desc..temp;

    end

    -- 由于不需要applyString，拼接好的描述信息中的颜色标示符需要去掉
    desc = extractString(desc);

    -- 神器属性描述
    local propLabel = findChildByName(CT, "prop");
    local kerning = -3;

    if getLang() ~= "zh" and getLang() ~= "tw" then
        kerning = -1;
    end

    TextStyleM.setTextStyle(propLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BLUE, false);
    propLabel:getVirtualRenderer():setAdditionalKerning(kerning);
    propLabel:setString(string.format(getLocStr("artifact_upgrade_help"), desc));

    -- 消耗
    local costLabel = findChildByName(CT, "cost");
    TextStyleM.setTextStyle(costLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN, false);

    local moneyCount = ME.user:queryAttrib("money");
    local costStr = getLocStr("artifact_upgrade_cost");
    local scrapColor = "[blue]%d[-]";
    local relicColor = "[blue]%d[-]";
    local moneyColor = "[blue]%d[-]";

    local ret = ArtifactM.canUpgrade(self.classId);
     -- 获取该等级升级的消耗
    local cost = ArtifactM.getUpgradeCost(self.classId);
    if #cost == 2 then
        if ret ~= true then
            local btnOk = findChildByName(node, "CT/btn_ok");
            btnOk:setBright(false);
            btnOk:setTouchEnabled(false);

            for _, arr in pairs(cost) do
                if arr[1] == 1 then
                    if ItemM.getAmount(ME.user, arr[2]) < arr[3] then
                        scrapColor = "[red]%d[-]";
                    end
                elseif arr[1] == 2 then
                    if ME.user:queryAttrib(arr[2]) < arr[3] then
                        moneyColor = "[red]%d[-]";
                    end
                end
            end
        end
        local str =  string.format(costStr, scrapColor, moneyColor);
        applyString(costLabel, string.format(str, needScrapNum, needMoneyNum));
    elseif #cost == 3 then
        local costStr2 = getLocStr("artifact_upgrade_cost2");
        local relicName;
        if ret ~= true then
            local btnOk = findChildByName(node, "CT/btn_ok");
            btnOk:setBright(false);
            btnOk:setTouchEnabled(false);
        end

        for _, arr in pairs(cost) do
            if arr[1] == 1 then
                if ArtifactM.isArtifactScrap(arr[2]) then
                    if ItemM.getAmount(ME.user, arr[2]) < arr[3] then
                        scrapColor = "[red]%d[-]";
                    end
                else
                    relicName = ItemM.query(arr[2], "name");
                    if ItemM.getAmount(ME.user, arr[2]) < arr[3] then
                        relicColor = "[red]%d[-]";
                    end
                end
            elseif arr[1] == 2 then
                if ME.user:queryAttrib(arr[2]) < arr[3] then
                    moneyColor = "[red]%d[-]";
                end
            end
        end

        local str =  string.format(costStr2, scrapColor, relicColor, relicName, moneyColor);
        applyString(costLabel, string.format(str, needScrapNum, needRelicNum, needMoneyNum));
        local pos = cc.p(self.btnOk:getPosition());
        self.btnOk:setPosition(pos.x, self.btnOkPosY - 20);
    end
end

-- 注册事件处理回调函数
function UIArtifactUpgrade:registerEventCallback()

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            EventMgr.removeAll("UIArtifactUpgrade");
        elseif eventType == "enter" then
        end
    end);

    -- 关注修复成功的事件
    EventMgr.register("UIArtifactUpgrade", event.ARTIFACT_UPGRADE, function(args)
         local uiArtiafactEffect =UIArtifactEffect.create(self.classId, "upgrade");
         UIMgr.getCurrentScene():addForm(uiArtiafactEffect);

         -- 如果更新到了最大级应该直接关闭强化页
        local artifactLevel = ArtifactM.getArtifactLevel(args.classId);
        if self.maxLevel == artifactLevel then
            UIMgr.getCurrentScene():removeFormByName("UIArtifactUpgrade");
        end
    end);

end

-- 注册点击事件
function UIArtifactUpgrade:registerTouchEvent()
    local node = self.node;

    -- 注册返回按钮点击事件
    local btnBack = findChildByName(node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");
            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UIArtifactUpgrade");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 注册确认按钮点击事件
    local btnOk = findChildByName(node, "CT/btn_ok");
    local function onOKClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");

            -- 客户端预判是否可以升级
            local ret = ArtifactM.canUpgrade(self.classId);
            if ret ~= true then
                alert(getLocStr(ret));
                return;
            end

            -- 向服务器发送神器合成请求
            Operation.cmd_upgrade_artifact(self.classId);
        end
    end
    btnOk:addTouchEventListener(onOKClick);
    TextStyleM.setTextStyle(btnOk, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnOk:setTitleText(getLocStr("btn_text_intensify"));
end

-- 显示神器详细界面
function UIArtifactUpgrade:showDetailInfo(id, type)
    self.isLongPress = true;

    local uiItemDesc = UIEquipTooltip.create(id, type);
    UIMgr:getCurrentScene():addForm(uiItemDesc);
end